package com.jlnk.petdemo.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.jlnk.petdemo.entity.PetModel;
import com.jlnk.petdemo.entity.PetResponse;
import com.jlnk.petdemo.repository.PetRepository;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PetViewModel extends ViewModel {
    private final PetRepository petRepository;
    private final MutableLiveData<List<PetModel>> petListLiveData = new MutableLiveData<>();

    public PetViewModel(PetRepository petRepository) {
        this.petRepository = petRepository;
    }

    public LiveData<List<PetModel>> getPetList() {
        return petListLiveData;
    }

    public void searchPets(String query, int type, int page, int num) {
        petRepository.getPetList(query, type, page, num, new Callback<PetResponse>() {
            @Override
            public void onResponse(Call<PetResponse> call, Response<PetResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    PetResponse petResponse = response.body();
                    if (petResponse.getError_code() == 0 && petResponse.getResult() != null && petResponse.getResult().getList() != null) {
                        petListLiveData.postValue(petResponse.getResult().getList());
                    } else {
                        petListLiveData.postValue(null);
                    }
                } else {
                    petListLiveData.postValue(null);
                }
            }

            @Override
            public void onFailure(Call<PetResponse> call, Throwable t) {
                petListLiveData.postValue(null);
            }
        });
    }
}